<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:productInfo:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:productInfo:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:productInfo:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:productInfo:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" align="center" prop="id"/>
      <el-table-column label="商品名称" align="center" prop="name"/>
      <el-table-column label="商品描述" align="center" prop="productDesc">
        <template slot-scope="scope">
          <p v-html="scope.row.productDesc"></p>
        </template>
      </el-table-column>
      <el-table-column label="商品主图" align="center" prop="img">
        <template slot-scope="scope">
          <img :src="scope.row.img" style="width: 100px; height: 100px;">
        </template>
      </el-table-column>
      <el-table-column label="商品轮播图" align="center" prop="carouselImages">
        <template slot-scope="scope">
          <img :src="scope.row.carouselImages" style="width: 100px; height: 100px;">
        </template>
      </el-table-column>
      <el-table-column label="品牌信息" align="center" prop="brand"/>
      <el-table-column label="商品状态" align="center" prop="status"/>
      <el-table-column label="单位" align="center" prop="unit"/>
      <el-table-column label="规格信息" align="center" prop="ruleId"/>
      <el-table-column label="0：添加商品信息 1：添加规格信息 2：添加描述信息" align="center" prop="step"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:productInfo:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:productInfo:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-steps :active="active" finish-status="success">
          <el-step title="添加商品信息"></el-step>
          <el-step title="添加规格信息"></el-step>
          <el-step title="添加描述信息"></el-step>
        </el-steps>
        <div v-show="active==0">
          <el-row :gutter="24">
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="商品名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入商品名称"/>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="单位" prop="unit">
                  <el-input v-model="form.unit" placeholder="请输入单位"/>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="品牌信息" prop="brand">
                  <el-select v-model="form.brand" placeholder="请选择品牌信息">
                    <el-option
                      v-for="item in brandInfoList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="分类" prop="type">
                  <el-cascader
                    v-model="form.type"
                    :options="categoryList"
                    :props=CascaderProps
                    @change="handleChange"
                  ></el-cascader>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-form-item label="商品主图" prop="img">
            <ImageUpload v-model="form.img" limit="1"></ImageUpload>
          </el-form-item>
          <el-form-item label="商品轮播图" prop="carouselImages">
            <ImageUpload v-model="form.carouselImages"></ImageUpload>
          </el-form-item>
        </div>
        <div v-show="active==1">
          <el-form-item label="规格信息" prop="ruleId">
            <el-select v-model="form.ruleId" placeholder="请选择规格信息" v-on:change="changeRuleInfoListByRuleId">
              <el-option
                v-for="item in ruleInfoList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form ref="form" :model="skuFormTemplate" label-width="80px">
            <el-form-item label="商品库存">
              <el-input-number v-model="skuFormTemplate.stock" :min="1" :max="999999999999999" label="商品库存"
                               style="width: 100px;"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="商品价格">
              <el-input-number v-model="skuFormTemplate.price" :min="1" :max="999999999999999" label="商品价格"
                               style="width: 100px;"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="商品进价">
              <el-input-number v-model="skuFormTemplate.purchasePrice" :min="1" :max="999999999999999" label="商品进价"
                               style="width: 100px;"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="商品售价">
              <el-input-number v-model="skuFormTemplate.sellingPrice" :min="1" :max="999999999999999" label="商品售价"
                               style="width: 100px;"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="规格图片">
              <ImageUpload v-model="skuFormTemplate.image" :limit="1"></ImageUpload>
            </el-form-item>
            <el-form-item label="编号">
              <el-input-number v-model="skuFormTemplate.number" :min="1" :max="999999999999999" label="编号"
                               style="width: 100px;"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="重量">
              <el-input-number v-model="skuFormTemplate.weight" :min="1" :max="999999999999999" label="重量"
                               style="width: 100px;"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="体积">
              <el-input-number v-model="skuFormTemplate.volume" :min="1" :max="999999999999999" label="体积"
                               style="width: 100px;"
              ></el-input-number>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSettings">立即创建</el-button>
              <el-button type="primary" @click="onClear">取消</el-button>
            </el-form-item>
          </el-form>
          <template>
            <el-table
              :data="tableBodyTemplate"
              style="width: 100%"
            >
              <el-table-column v-for="column in tableColumHeaderTemplate"
                               :prop="column.prop"
                               :label="column.label"
              >
                <template slot-scope="scope">
                  <el-input-number v-if="column.prop.indexOf('image') == -1 && column.prop.indexOf('xxx') == -1"
                                   v-model="scope.row[column.prop]" :min="1" :max="999999999999999" label="描述文字"
                                   style="width: 100px;"
                  ></el-input-number>
                  <ImageUpload v-else-if="column.prop.indexOf('image') > -1" v-model="scope.row[column.prop]" limit="1"
                  ></ImageUpload>
                  <span v-else>{{ scope.row[column.prop] }}</span>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </div>
        <div v-show="active==2">
          <el-form-item label="商品描述" prop="productDesc">
            <el-input v-model="form.productDesc" type="textarea" placeholder="请输入内容"/>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="margin-top: 12px;" @click="pre" :disabled="active<1">上一步</el-button>
        <el-button style="margin-top: 12px;" @click="next" :disabled="active>=2">下一步</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProductInfo,
  getProductInfo,
  delProductInfo,
  addProductInfo,
  updateProductInfo
} from '@/api/product/productInfo'
import ImageUpload from '@/components/ImageUpload'
import { listProductbrandInfo } from '@/api/product/productbrandInfo'
import { listCategoryAll } from '@/api/product/category'
import { listRuleInfo } from '@/api/product/ruleInfo'
import imageUpload from '@/components/ImageUpload/index.vue'

export default {
  name: 'ProductInfo',
  components: {
    ImageUpload
  },
  data() {
    return {
      CascaderProps: { expandTrigger: 'hover', value: 'catId', label: 'name', children: 'chiledrenList' },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品信息表格数据
      productInfoList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      stepsMap: {
        0: '添加商品信息',
        1: '添加规格信息',
        2: '添加描述信息',
        '添加商品信息': 0,
        '添加规格信息': 1,
        '添加描述信息': 2
      },
      active: 0,
      brandInfoList: [],
      categoryList: [],
      ruleInfoList: [],
      tableColumHeaderTemplate: [],
      tableBodyTemplate: [
        /* {'stock':'商品库存1', price:'1', purchasePrice:'1', sellingPrice:'1', image:'', number:'1', weight:'1',volume:'1'},
        {'stock':'商品库存2', price:'1', purchasePrice:'1', sellingPrice:'1', image:'', number:'1', weight:'1',volume:'1'},
        {'stock':'商品库存3', price:'1', purchasePrice:'1', sellingPrice:'1', image:'', number:'1', weight:'1',volume:'1'},
        {'stock':'商品库存4', price:'1', purchasePrice:'1', sellingPrice:'1', image:'', number:'1', weight:'1',volume:'1'},
        {'stock':'商品库存5', price:'1', purchasePrice:'1', sellingPrice:'1', image:'', number:'1', weight:'1',volume:'1'},
        {'stock':'商品库存6', price:'1', purchasePrice:'1', sellingPrice:'1', image:'', number:'1', weight:'1',volume:'1'},
        {'stock':'商品库存7', price:'1', purchasePrice:'1', sellingPrice:'1', image:'', number:'1', weight:'1',volume:'1'},
        {'stock':'商品库存8', price:'1', purchasePrice:'1', sellingPrice:'1', image:'', number:'1', weight:'1',volume:'1'},
        {'stock':'商品库存9', price:'1', purchasePrice:'1', sellingPrice:'1', image:'', number:'1', weight:'1',volume:'1'} */
      ],
      skuFormTemplate: {
        stock: '0',
        price: '0',
        purchasePrice: '0',
        sellingPrice: '0',
        image: '',
        number: '0',
        weight: '0',
        volume: '0'
      }
    }
  },
  created() {
    this.getList()
    this.initBrandList()
    this.initcategoryList()
    this.initListRuleInfo()
  },
  methods: {

    onSettings() {
      this.SettingsOrClear(true);
    },

    onClear() {
      this.SettingsOrClear();
    },
    SettingsOrClear(flag){
      for (let skuFormTemplateKey in this.skuFormTemplate) {
        this.tableBodyTemplate.forEach(item => {
          for (let itemKey in item) {
            if (skuFormTemplateKey === itemKey) {
              if(flag){
                item[itemKey] = this.skuFormTemplate[skuFormTemplateKey]
              }else {
                item[itemKey] = '';
              }
            }
          }
        })
      }
    },
    changeRuleInfoListByRuleId(object) {
      this.tableColumHeaderTemplate = []
      this.tableBodyTemplate = []
      let ruleInfo = null
      this.ruleInfoList.forEach(res => {
        if (object == res.id) {
          ruleInfo = res
        }
      })
      if (null == ruleInfo) {
        return
      }
      let ruleAttrJson = JSON.parse(ruleInfo.ruleAttr)
      ruleAttrJson.forEach((ruleAttr, index) => {
        this.tableColumHeaderTemplate.push({ 'prop': `xxx${index}`, 'label': ruleAttr.ruleType })
      })

      const cartesian = (ruleAttrJson, index, current) => {
        if (index === ruleAttrJson.length) {
          this.tableBodyTemplate.push({ ...current })
          return
        }
        for (let i = 0; i < ruleAttrJson[index].ruleAttrList.length; i++) {
          current[`xxx${index}`] = ruleAttrJson[index].ruleAttrList[i]
          current[`image`] = ''
          cartesian(ruleAttrJson, index + 1, { ...current })
        }
      }
      cartesian(ruleAttrJson, 0, {})

      this.tableBodyTemplate.forEach(item=>{
        let sku = [];
        for (let itemKey in item) {
          if(itemKey.indexOf('xxx') > -1){
            sku.push(item[itemKey])
          }
        }
        sku = sku.join(",");
        item['sku'] = sku;
      });

      this.tableColumHeaderTemplate.push(
        { prop: 'stock', label: '商品库存' },
        { prop: 'price', label: '商品价格' },
        { prop: 'purchasePrice', label: '商品进价' },
        { prop: 'sellingPrice', label: '商品售价' },
        { prop: 'image', label: '规格图片' },
        { prop: 'number', label: '编号' },
        { prop: 'weight', label: '重量' },
        { prop: 'volume', label: '体积' })
    },

    initListRuleInfo() {
      let pat = {
        status: 0
      }
      listRuleInfo(pat).then(res => {
        if (200 === res.code) {
          this.ruleInfoList = res.data.rows
        }
      })
    },

    initcategoryList() {
      listCategoryAll().then(res => {
        if (200 === res.code) {
          this.categoryList = res.data
        }
      })
    },

    initBrandList() {
      let params = {
        status: 0
      }
      listProductbrandInfo(params).then(res => {
        if (200 === res.code) {
          this.brandInfoList = res.data.rows
        }
      })
    },

    pre() {
      this.active--
    },
    next() {
      this.active++
    },

    /** 查询商品信息列表 */
    getList() {
      this.loading = true
      listProductInfo(this.queryParams).then(response => {
        let productInfoList = response.data.rows
        productInfoList.forEach(res => {
          res.step = this.switchStepByNum(res.step)
        })
        this.productInfoList = productInfoList
        this.total = response.data.total
        this.loading = false
      })
    },

    switchStepByNum(num) {
      if (num == null || num == '' || num == undefined) {
        this.$modal.msgWarning('num is Null')
        return
      }
      for (let stepsMapKey in this.stepsMap) {
        if (num == stepsMapKey) {
          return this.stepsMap[stepsMapKey]
        }
      }
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.active = 0
      this.tableColumHeaderTemplate = []
      this.tableBodyTemplate = []
      this.form = {
        id: null,
        name: null,
        productDesc: null,
        type: null,
        typeIds: null,
        img: null,
        carouselImages: null,
        commentCount: null,
        collectCount: null,
        brand: null,
        status: null,
        unit: null,
        keywords: null,
        ruleId: null,
        revision: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        step: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.skuFormTemplate = {}
      this.open = true
      this.title = '添加商品信息'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getProductInfo(id).then(response => {
        let data = response.data
        this.active = data.step
        let ruleId = data.ruleId
        this.changeRuleInfoListByRuleId(ruleId)
        if (data.skuInfoList && data.skuInfoList.length > 0) {
          data.skuInfoList.forEach(item => {
            if (item.sku) {
              let skuArray = item.sku.split(",");
              for (let i = 0; i < skuArray.length; i++) {
                item[`xxx${i}`] = skuArray[i];
              }
            }
          });
        }

        this.tableBodyTemplate = data.skuInfoList;


        this.form = data
        let typeList = []
        let type = data.typeIds.split(",")
        type.forEach(item=>{
          typeList.push(item*1)
        })
        this.form.type = typeList;
        this.open = true
        this.title = '修改商品信息'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          let typeIds = this.form.type.join(",");
          let type = this.form.type[this.form.type.length - 1];
          this.form.step = this.active;
          this.form.typeIds = typeIds;
          this.form.type = type;

          this.form["skuInfoList"] = this.tableBodyTemplate;

          if (this.form.id != null) {
            updateProductInfo(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addProductInfo(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除商品信息编号为"' + ids + '"的数据项？').then(function() {
        return delProductInfo(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('product/productInfo/export', {
        ...this.queryParams
      }, `productInfo_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
